#include "stdafx.h"
#include "mainwindow.h"
#include "http_client.h"
#include "http_server.h"

http_server::http_server(http_service& service, const char *ip, int port,
                         MainWindow *parent)
: service_(service), ip_(ip), port_(port), parent_(parent)
{
    box_ = new acl::fiber_tbox<bool>;
}

http_server::~http_server() {
    delete box_;
}

void http_server::stop() {
    box_->pop();
}

void http_server::run() {
    server_start();
}

void http_server::server_start() {
    acl::string addr;
    addr.format("%s|%d", ip_.c_str(), port_);
    acl::server_socket ss;

    if (!ss.open(addr)) {
        qDebug() << "Listen " << addr.c_str() << " error: " << acl::last_serror();
        return;
    }

    qDebug() << "Listen " << addr.c_str() << " ok!";

    while (true) {
        acl::socket_stream* conn = ss.accept();
        if (conn == nullptr) {
            qDebug() << "Accept error: %s" << acl::last_serror();
            break;
        }
        qDebug() << "Start one fiber for peer: " << conn->get_peer(true);

        go[this, conn] {
            qDebug() << "Begin handle http client";
            http_client client(*this, *conn);
            client.start();
            delete conn;
        };
    }
    box_->push(nullptr);
}
